package My

import (
	"fmt"
	"db2s/ETL"
	"db2s/global"
	"strings"
)

func (my TableInfoMeta) JobName(s global.TablesMetaInfoInput) (result global.ObjectNameReturnResult, err error) {
	var f1 any
	var event = "[MySQLJobName]"
	result.BaseResult.Sql = fmt.Sprintf("select EVENT_NAME from information_Schema.events where EVENT_SCHEMA ='%v' %v",
		s.TableInfo.Schema, func() string {
			switch {
			case s.TableInfo.Table == "*":
				return ""
			case strings.Contains(s.TableInfo.Table, "%"):
				return fmt.Sprintf(" and EVENT_NAME like '%%%v%%'", s.TableInfo.Table)
			default:
				return fmt.Sprintf(" and EVENT_NAME = '%v'", s.TableInfo.Table)
			}
		}())
	if result.BaseResult.TimeOut, f1, err = ExecSelectSql(ExecSqlInputS{
		Ss:           s,
		Event:        event,
		SelectSqlStr: result.BaseResult.Sql,
		Expect:       ETL.StringGarth,
	}); err != nil || f1 == nil {
		return
	}
	result.Result = f1.([]string)
	return
}

func (my TableInfoMeta) JobExist(s global.TablesMetaInfoInput) (result global.ObjectExistReturnResult, err error) {
	var f1 any
	var event = "[MySQLJobExist]"
	result.BaseResult.Sql = fmt.Sprintf("select count(1) as `sum` from information_schema.events where EVENT_SCHEMA ='%v'  and EVENT_NAME = '%v'", s.TableInfo.Schema, s.TableInfo.Table)
	if result.BaseResult.TimeOut, f1, err = ExecSelectSql(ExecSqlInputS{
		Ss:           s,
		Event:        event,
		SelectSqlStr: result.BaseResult.Sql,
		Expect:       ETL.Map,
	}); err != nil || f1 == nil {
		return
	}
	if fmt.Sprintf("%v", f1.(map[string]any)["sum"]) == "1" {
		result.Result = true
	}
	return
}

func (my SchemaObjectMeta) Job(s global.SchemaObjectInput) (result global.SchemaObjectReturnResult, err error) {
	var f1 any
	var event = "[MySQLJob]"
	result.BaseResult.Sql = fmt.Sprintf("SELECT `EVENT_NAME` as `jobName`,`EVENT_BODY` as `jobType`, \n"+
		"`EVENT_DEFINITION` as `jobDefinition`,`LAST_EXECUTED` as `startDate`,concat(`INTERVAL_VALUE`,' ',`INTERVAL_FIELD`) as `interval`, \n"+
		"`INTERVAL_FIELD` as `intervalField`,`INTERVAL_VALUE` as `intervalValue`,`STATUS` as `enable`,`EVENT_COMMENT` as `comment` \n"+
		"FROM `INFORMATION_SCHEMA`.`EVENTS` \n"+
		"where 1=1 and EVENT_SCHEMA = '%v' and EVENT_NAME = '%v'", s.Schema, s.Table)
	if result.BaseResult.TimeOut, f1, err = ExecSelectSql(ExecSqlInputS{
		Ss:           s,
		Event:        event,
		SelectSqlStr: result.BaseResult.Sql,
		Expect:       ETL.Map,
	}); err != nil || f1 == nil {
		return
	}
	var x global.JobResultDefinition
	if err = global.MapSubToStructSubJsonName(f1.(map[string]any), &x); err != nil {
		return
	}
	result.JobResult.Definition = x
	return
}
func JobSwitchConvert(s string) (res string) {
	switch s {
	case "TRUE":
		res = "ENABLE"
	case "FALSE":
		res = "DISABLE"
	}
	return
}
func jobIntervalConvert(s global.JobInterval) (res string) {
	switch {
	case s.TimeFrequency.Year > 0:
		return fmt.Sprintf(" %v YEAR", s.TimeFrequency.Year)
	case s.TimeFrequency.Month > 0:
		return fmt.Sprintf(" %v MONTH", s.TimeFrequency.Month)
	case s.TimeFrequency.Week > 0:
		return fmt.Sprintf("%v WEEK", s.TimeFrequency.Week)
	case s.TimeFrequency.Day > 0:
		return fmt.Sprintf(" %v DAY", s.TimeFrequency.Day)
	case s.TimeFrequency.Hour > 0:
		if s.TimeFrequency.Minute/60 == s.TimeFrequency.Hour && s.TimeFrequency.Minute%60 > 0 {
			return fmt.Sprintf(" %v HOUR %v MINUTE", s.TimeFrequency.Hour, s.TimeFrequency.Minute%60)
		}
		return fmt.Sprintf(" %v HOUR", s.TimeFrequency.Hour)
	case s.TimeFrequency.Minute > 0:
		if s.TimeFrequency.Second/60 == s.TimeFrequency.Minute && s.TimeFrequency.Second%60 > 0 {
			return fmt.Sprintf(" %v MINUTE %v SECOND", s.TimeFrequency.Minute, s.TimeFrequency.Second%60)
		}
		return fmt.Sprintf(" %v MINUTE", s.TimeFrequency.Minute)
	case s.TimeFrequency.Second > 0:
		return fmt.Sprintf(" %v SECOND", s.TimeFrequency.Second)
	}
	return
}
func createJob(s global.SchemaObjectInput) (result global.ObjectFixSqlS, err error) {
	result.CreateSql = append(result.CreateSql, fmt.Sprintf("use %v; \n"+
		"delimiter $$ \n"+
		"CREATE EVENT `%v` \n"+
		"ON SCHEDULE \n"+
		"	EVERY %v \n"+
		"STARTS str_to_date('%v','%%Y-%%m-%%d %%H:%%i:%%s') \n"+
		"%v \n"+
		"COMMENT '%v' \n"+
		"DO \n"+
		"BEGIN \n"+
		"  %v \n"+
		"END; \n"+
		"$$ \n"+
		"delimiter ;",
		s.Schema,
		s.ObjectDefinition.JobResult.Convert.Name,
		jobIntervalConvert(s.ObjectDefinition.JobResult.Convert.Interval),
		s.ObjectDefinition.JobResult.Convert.StartTime,
		JobSwitchConvert(s.ObjectDefinition.JobResult.Convert.JobStatus),
		strings.ReplaceAll(s.ObjectDefinition.JobResult.Convert.Description, "'", "\\'"),
		func() string {
			var rr []string
			for _, v := range s.ObjectDefinition.JobResult.Convert.BodyPrepare {
				switch v.ExecType {
				case "func/proc":
					rr = append(rr, fmt.Sprintf(" call %v(); ", v.BodyModify))
				case "dblink":
					if len(v.BodyModify) > 0 {
						rr = append(rr, fmt.Sprintf(" %v; ", v.BodyModify))
					} else {
						rr = append(rr, fmt.Sprintf(" %v; ", v.BodyOld))
					}
				default:
					rr = append(rr, fmt.Sprintf(" %v; ", v.BodyOld))
				}
			}
			return strings.Join(rr, "\n")
		}(),
	))
	return
}
